//
//  SettingViewController.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 12-12-7.
//  Copyright (c) 2012年 wzyk. All rights reserved.
//

#import "SettingViewController.h"
#import "SDImageCache.h"
#import "ASIDownloadCache.h"
#import "SinaWeiboManager.h"
#import <QuartzCore/QuartzCore.h>
#import "SuggestViewController.h"

@interface SettingViewController ()
{
    long size;
    BOOL manualRefresh;
    BOOL shouldRotate;
}
@end

@implementation SettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sinaWeiboLogStateDidChange) name:kSinaWeiboLogStateDidChange object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotAppUpdateInfo:) name:gotAppUpdateInfoNotify object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    contentScrollView.contentSize = CGSizeMake(320, 436);
    [self updateDiaplay];
}

- (void)updateDiaplay
{
    wifiSwitch.on = ![[DownloadManager defaultManager] WWANDownloadEnable];
    sinaweiboSwitch.on = [[[SinaWeiboManager defaultManager] sinaweibo] isAuthValid];
    [self getCacheSize];
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey:(NSString *)kCFBundleVersionKey];
    versionLabel.text = [NSString stringWithFormat:@"v%@",localVersion];
}

- (void)getCacheSize
{
    clearButton.hidden = YES;
    clearIndicator.hidden = NO;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //网络图片缓存
        float imageCacheSize = [[SDImageCache sharedImageCache] getSize]/1024.00/1024.00;
        //
        NSString *asiDownlaodCachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ASIHTTPRequestCache"];
        size = 0;
        [self fileSizeForDir:asiDownlaodCachePath];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            float totalSize = imageCacheSize + size/1024.00/1024.00;
            if (totalSize == 0) {
                cacheLabel.text = [NSString stringWithFormat:@"清除缓存（0 M）"];
            }
            else {
                cacheLabel.text = [NSString stringWithFormat:@"清除缓存（%.1f M）",imageCacheSize + size/1024.00/1024.00];
            }
            clearButton.hidden = NO;
            clearIndicator.hidden = YES;
        });
    });
}

-(long)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
            size+= fileAttributeDic.fileSize;
        }
        else
        {
            [self fileSizeForDir:fullPath];
        }
    }
    [fileManager release];
    return size;
}

- (IBAction)clearAction:(id)sender {
    clearButton.hidden = YES;
    clearIndicator.hidden = NO;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *asiDownlaodCachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ASIHTTPRequestCache"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:asiDownlaodCachePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:asiDownlaodCachePath error:nil];
        }
        [[SDImageCache sharedImageCache] clearDisk];
        [[SDImageCache sharedImageCache] clearMemory];
        dispatch_async(dispatch_get_main_queue(), ^{
            clearButton.hidden = NO;
            clearIndicator.hidden = YES;
            [self getCacheSize];
        });
    });
}

- (IBAction)wifSwitchAction:(id)sender {
    [[DownloadManager defaultManager] setWWANDownloadEnable:!wifiSwitch.on];
}

- (void)sinaWeiboLogStateDidChange
{
    sinaweiboSwitch.on = [[[SinaWeiboManager defaultManager] sinaweibo] isAuthValid];
}

- (IBAction)sinaweiboSwitchAction:(id)sender
{
    if (sinaweiboSwitch.on) {
        [[[SinaWeiboManager defaultManager] sinaweibo] logIn];
    }
    else {
        [[[SinaWeiboManager defaultManager] sinaweibo] logOut];
    }
}

- (IBAction)update:(id)sender
{
    manualRefresh = YES;
    [[DataRequest sharedRequest] getAppUpdateInfo];
    shouldRotate = YES;
    [self animateRefreshButton];
}

- (void)gotAppUpdateInfo:(NSNotification *)notification
{
    shouldRotate = NO;//停止转动
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *currentVersion = [result objectForKey:@"now"];
            NSDictionary *lastVersion = [result objectForKey:@"new"];
            
            if (lastVersion == nil) {
                //当前为最新版
                if (manualRefresh) {
                    //手动刷新时显示下期预告
                    NSString *notice = [currentVersion objectForKey:@"update_notice"];
//                    notice = [notice stringByReplacingOccurrencesOfString:@"\\\\n" withString:@"\n\t"];
                    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"当前为最新版本" message:notice delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] autorelease];
                    [alertView show];
                }
            }
            else {
                //当前不是最新版本
                if ([[currentVersion objectForKey:@"disabled"] boolValue]) {
                    //当前版本已不可用
                    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"发现新版本v%.2f",[[lastVersion objectForKey:@"version"] floatValue]] message:[lastVersion objectForKey:@"update_content"] delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"更新", nil] autorelease];
                    alertView.tag = 1;
                    [alertView show];
                }
                else {
                    //当前版本仍可用
                    NSDate *date = [[[NSUserDefaults standardUserDefaults] objectForKey:kNextUpdateDate] dateValue];
                    if (manualRefresh || (date == nil || [date timeIntervalSinceNow] < 0)) {
                        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"发现新版本v%.2f",[[lastVersion objectForKey:@"version"] floatValue]] message:[lastVersion objectForKey:@"update_content"] delegate:self cancelButtonTitle:@"稍后提醒" otherButtonTitles:@"更新", nil] autorelease];
                        alertView.tag = 2;
                        [alertView show];
                    }
                }
            }
        }
    }
    manualRefresh = NO;
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kNextUpdateDate];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (buttonIndex == 0) {
            exit(1);
        }
        else if (buttonIndex == 1) {
            [self gotoAppStore];
        }
    }
    else if (alertView.tag == 2) {
        if (buttonIndex == 0) {
            NSDate *data = [NSDate dateWithTimeIntervalSinceNow:12 * 60 * 60];
            [[NSUserDefaults standardUserDefaults] setObject:data forKey:kNextUpdateDate];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else if (buttonIndex == 1) {
            [self gotoAppStore];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kNextUpdateDate];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
}

- (void)gotoAppStore
{
    NSURL *appURL = [NSURL URLWithString:[AppURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [[UIApplication sharedApplication] openURL:appURL];
}

- (void)animateRefreshButton
{
    static int rotateTimes = 1;
    static BOOL animating = NO;
    
    if (!animating) {
        refreshButton.transform = CGAffineTransformMakeRotation(0);
    }
    animating = YES;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        refreshButton.transform = CGAffineTransformMakeRotation(M_PI_2 * rotateTimes);
    } completion:^(BOOL finished) {
        if (finished) {
            if (shouldRotate) {
                rotateTimes ++;
                [self animateRefreshButton];
            }
            else {
                animating = NO;
                refreshButton.transform = CGAffineTransformMakeRotation(0);
                rotateTimes = 1;
            }
        }
        else {
            animating = NO;
            refreshButton.transform = CGAffineTransformMakeRotation(0);
            rotateTimes = 1;
        }
    }];
}

-(IBAction)goToAppStoreComment
{
    NSString *str = [NSString stringWithFormat:
                     @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d",624436405];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (IBAction)showSuggestView:(id)sender
{
    SuggestViewController *suggestViewController = [[[SuggestViewController alloc] initWithNibName:@"SuggestViewController" bundle:nil] autorelease];
    
    UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
    [navController pushViewController:suggestViewController animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [cacheLabel release];
    [wifiSwitch release];
    [clearButton release];
    [clearIndicator release];
    [sinaweiboSwitch release];
    [versionLabel release];
    [refreshButton release];
    [contentScrollView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [cacheLabel release];
    cacheLabel = nil;
    [wifiSwitch release];
    wifiSwitch = nil;
    [clearButton release];
    clearButton = nil;
    [clearIndicator release];
    clearIndicator = nil;
    [sinaweiboSwitch release];
    sinaweiboSwitch = nil;
    [versionLabel release];
    versionLabel = nil;
    [refreshButton release];
    refreshButton = nil;
    [contentScrollView release];
    contentScrollView = nil;
    [super viewDidUnload];
}
@end
